import json
import logging
import time
import requests

def query_token_from_api(username,pw):
    url = "https://agent.api.sneakerburgers.com/api/accountservice/open/login"
    payload="{\"username\":\"%s\",\"password\":\"%s\"}"%(username,pw)
    headers = {
      'authority': 'agent.api.sneakerburgers.com',
      'accept': 'application/json, text/plain, */*',
      'authorization': 'undefined',
      'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
      'os': 'web',
      'content-type': 'application/json;charset=UTF-8',
      'origin': 'https://agent.sneakerburgers.com',
      'sec-fetch-site': 'same-site',
      'sec-fetch-mode': 'cors',
      'sec-fetch-dest': 'empty',
      'referer': 'https://agent.sneakerburgers.com/',
      'accept-language': 'zh-CN,zh;q=0.9'
    }

    response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8")).json()
    return response["data"]

def get_login_token():
    files_path = "config.json"
    current_time=int(time.time())
    with open(files_path,encoding="utf-8") as f1:
        config=json.load(f1)
    if config["login_info"]["fetch_now"]=="false" and current_time-config["login_info"]["last_time"]<config["login_info"]["interval"]:
        logging.warning("fetch login info from config, username=" + config["login_info"]["username"])
        return config["login_info"]["token"]
    else:
        token=query_token_from_api(config["login_info"]["username"],config["login_info"]["password"])
        logging.warning("fetch login info from api, username=" + config["login_info"]["username"])
        config["login_info"]["token"]=token
        config["login_info"]["last_time"] = current_time
        config["login_info"]["fetch_now"] = "false"
        with open(files_path, 'w') as f2:
            f2.write(json.dumps(config, ensure_ascii=True))
        return token


def get_login_token_PJ():
    files_path = "config.json"
    current_time=int(time.time())
    with open(files_path,encoding="utf-8") as f1:
        config=json.load(f1)
    if config["login_info_PJ"]["fetch_now"]=="false" and current_time-config["login_info_PJ"]["last_time"]<config["login_info_PJ"]["interval"]:
        logging.warning("fetch login info from config, username=" + config["login_info_PJ"]["username"])
        return config["login_info_PJ"]["token"]
    else:
        token=query_token_from_api(config["login_info_PJ"]["username"],config["login_info_PJ"]["password"])
        logging.warning("fetch login info from api, username=" + config["login_info_PJ"]["username"])
        config["login_info_PJ"]["token"]=token
        config["login_info_PJ"]["last_time"] = current_time
        config["login_info_PJ"]["fetch_now"] = "false"
        with open(files_path, 'w') as f2:
            f2.write(json.dumps(config, ensure_ascii=True))
        return token